import { login, getUserInfo } from '@/api/auth'

const state = {
  token: uni.getStorageSync('token') || '',
  userInfo: uni.getStorageSync('userInfo') || null,
  isLoggedIn: !!uni.getStorageSync('token')
}

const mutations = {
  SET_TOKEN(state, token) {
    state.token = token
    uni.setStorageSync('token', token)
  },
  SET_USER_INFO(state, userInfo) {
    state.userInfo = userInfo
    uni.setStorageSync('userInfo', userInfo)
  },
  SET_LOGIN_STATE(state, isLoggedIn) {
    state.isLoggedIn = isLoggedIn
  },
  CLEAR_USER(state) {
    state.token = ''
    state.userInfo = null
    state.isLoggedIn = false
    uni.removeStorageSync('token')
    uni.removeStorageSync('userInfo')
  }
}

const actions = {
  // 登录
  async login({ commit }, loginData) {
    try {
      const res = await login(loginData)
      commit('SET_TOKEN', res.token)
      commit('SET_USER_INFO', res.userInfo)
      commit('SET_LOGIN_STATE', true)
      return res
    } catch (error) {
      throw error
    }
  },

  // 获取用户信息
  async getUserInfo({ commit }) {
    try {
      const res = await getUserInfo()
      commit('SET_USER_INFO', res)
      return res
    } catch (error) {
      throw error
    }
  },

  // 退出登录
  logout({ commit }) {
    commit('CLEAR_USER')
  }
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
} 